<template>
	<div class="tui-conversation-list" v-cloak>
		<div class="oh" v-for="(conversation, index) in conversationList" :key="index"
			@click.stop="enterConversationChat(conversation.conversationID)">
			<div :class="['TUI-conversation-content', !isPC && 'TUI-conversation-content-h5', 'list_wrap', !!conversation.show && 'active']"
				@touchstart="touchStart" @touchend="touchEnd($event, conversation)">
				<view
					:class="[isPC && 'isPC', 'TUI-conversation-item', 'list_item', currentConversationID === conversation.conversationID && 'TUI-conversation-item-selected', conversation.isPinned && 'TUI-conversation-item-pinned']">
					<aside class="left left_pic">
						<Avatar useSkeletonAnimation :url="conversation.getAvatar()" :message="conversation.userProfile"
							size="88rpx" />
						<div v-if="userOnlineStatusMap && isShowUserOnlineStatus(conversation)"
							:class="['online-status', Object.keys(userOnlineStatusMap).length > 0 && Object.keys(userOnlineStatusMap).includes(conversation.userProfile.userID) && userOnlineStatusMap[conversation.userProfile.userID].statusType === 1 ? 'online-status-online' : 'online-status-offline']">
						</div>
						<span class="num" v-if="conversation.unreadCount > 0 && !conversation.isMuted">
							{{ conversation.unreadCount > 99 ? "99+" : conversation.unreadCount }}
						</span>
						<span class="num-notify" v-if="conversation.unreadCount > 0 && conversation.isMuted"></span>
					</aside>
					<div class="content left_content">
						<div class="content-header">
							<label class="content-header-label">
								<p class="name">{{ conversation.getShowName() }}</p>
								<p class="name" v-if="!!conversation.nick">{{ conversation.nick }}</p>
							</label>
							<div class="middle-box">
								<span class="middle-box-at"
									v-if="conversation.type === 'GROUP' && conversation.groupAtInfoList && conversation.groupAtInfoList.length > 0">{{ conversation.getGroupAtInfo() }}</span>
								<p class="middle-box-content">
									{{ transformText(conversation.getLastMessage("text")) }}
								</p>
							</div>
						</div>
						<div class="content-footer">
							<span class="time">{{ conversation.getLastMessage("time") }}</span>
							<Icon v-if="conversation.isMuted" :file="muteIcon"></Icon>
						</div>
					</div>
				</view>
				<div class="item_btn item_btn1" @click.stop="click(conversation, 0)">
					{{ lang === 'zh' ? '删除' : "Удалить" }}
				</div>
				<div class="item_btn item_btn2" @click.stop="click(conversation, 1)">
					{{ !conversation.isMuted ? (lang === 'zh' ? '免打扰' : "Без звука") : (lang === 'zh' ? '取消免打扰' : "Отменить режим без звука") }}
				</div>
				<div class="item_btn item_btn3" @click.stop="click(conversation, 2)">
					{{ !conversation.isPinned ? (lang === 'zh' ? '置顶' : "Закрепить") : (lang === 'zh' ? '取消置顶' : "Отменить закреп") }}
				</div>
			</div>
		</div>

		<Dialog :show="isShowDeleteConversationDialog" :center="true" :isHeaderShow="isPC"
			@submit="handleItem({ name: CONV_OPERATION.DELETE })" @update:show="updateShowDeleteConversationDialog">
			<p class="delDialog-title">
				{{TUITranslateService.t(deleteConversationDialogTitle)}}
			</p>
		</Dialog>
	</div>
</template>
<script lang="ts" setup>
	import Dialog from "../../common/Dialog/index.vue";
	import { CONV_OPERATION } from "../../../constant";

	import { ref, onMounted, onUnmounted, computed } from "../../../adapter-vue";
	import TUIChatEngine, {
		TUIStore,
		StoreName,
		TUIConversationService,
		TUITranslateService,
		IConversationModel,
	} from "@tencentcloud/chat-uikit-engine";
	import Icon from "../../common/Icon.vue";
	import Avatar from "../../common/Avatar/index.vue";
	import muteIcon from "../../../assets/icon/mute.svg";
	import { isPC } from "../../../utils/env";

	import { HTTP_REQUEST_URL, PERFIX } from '@/config/app.js';

	interface IUserStatus {
		statusType : number;
		customStatus : string;
	}

	interface IUserStatusMap {
		[userID : string] : IUserStatus;
	}

	const props = defineProps({
		lang: {
			type: String,
			default: "zh",
		}
	});

	// 删除判断
	const isShowDeleteConversationDialog = ref<boolean>(false);

	const emits = defineEmits(["handleSwitchConversation", "getPassingRef", "isReLoad"]);
	const currentConversation = ref<IConversationModel>();
	const currentConversationID = ref<string>();
	const isShowOverlay = ref<boolean>(false);
	const conversationList = ref<IConversationModel[] | any>([]);

	const displayOnlineStatus = ref(false); // 在线状态 默认关闭
	const userOnlineStatusMap = ref<IUserStatusMap>();

	let lastestOpenActionsMenuTime : number | null = null;

	// 删除弹窗文案内容
	const deleteConversationDialogTitle = computed(() => {
		let text = "";
		if (currentConversation.value?.type === TUIChatEngine.TYPES.CONV_C2C) {
			text = props.lang === 'zh' ? '删除后，将清空该聊天的消息记录' : "Удаление истории чата приведет к удалению всех сообщений";
		}
		if (currentConversation.value?.type === TUIChatEngine.TYPES.CONV_GROUP) {
			text = props.lang === 'zh' ? '删除后，将清空该群聊的消息记录' : "Удаление истории группового чата приведет к удалению всех сообщений";
		}
		return text;
	})

	const handleItem = (params : { name : string }) => {
		const { name } = params;
		const conversationModel = currentConversation.value;
		if (!name || !conversationModel || !conversationModel?.conversationID) {
			return;
		}
		switch (name) {
			case CONV_OPERATION.DELETE:
				conversationModel?.deleteConversation();
				break;
			case CONV_OPERATION.ISPINNED:
				conversationModel?.pinConversation();
				break;
			case CONV_OPERATION.DISPINNED:
				conversationModel?.pinConversation();
				break;
			case CONV_OPERATION.MUTE:
				conversationModel?.muteConversation();
				break;
			case CONV_OPERATION.NOTMUTE:
				conversationModel?.muteConversation();
				break;
		}
		closeConversationActionMenu();
	};

	// 滑块 start
	let clientX = ref<number>(0);
	let clientY = ref<number>(0);
	const touchStart = (e : any) => {
		clientX.value = e.changedTouches[0].clientX;
		clientY.value = e.changedTouches[0].clientY;
	}
	const touchEnd = (e : any, val : IConversationModel | undefined) => {
		if (!val) return;
		let diffX = clientX.value - e.changedTouches[0].clientX;
		if (Math.abs(diffX) < 80) return;
		let diffY = Math.abs(clientY.value - e.changedTouches[0].clientY);
		if ((diffY / Math.abs(diffX)) > 1) return;
		if (diffX > 0) {
			conversationList.value.map((item : IConversationModel) => {
				if (!!item.show) item.show = false;
			})
			val.show = true;
			currentConversation.value = val;
			lastestOpenActionsMenuTime = Date.now();
		}
		if (diffX < 0) val.show = false;
	}
	// 滑块 end

	// 滑块按钮点击
	const click = (item : IConversationModel, index1 : number) => {
		switch (index1) {
			case 0:
				isShowDeleteConversationDialog.value = true;
				break;
			case 1:
				handleItem({ name: CONV_OPERATION.MUTE })
				break;
			case 2:
				handleItem({ name: CONV_OPERATION.ISPINNED })
				break;
			default:
				break;
		}
		item.show = false;
	}

	const updateShowDeleteConversationDialog = (isShow : boolean) => {
		isShowDeleteConversationDialog.value = isShow;
	};
	let oldNum = ref<number>(0);
	onMounted(() => {

		TUIStore.watch(StoreName.CONV, {
			currentConversationID: (id : string) => {
				currentConversationID.value = id;
			},
			conversationList: (list : IConversationModel[]) => {
				let user_id = uni.getStorageSync("user_id");
				if (!user_id) {
					conversationList.value = [];
					return;
				}
				let arr : any[] = [];
				if (list?.length > 0) {
					list.map((item : any) => {
						item.show = false;
						arr.push(item);
					})
				}
				conversationList.value = arr;
				// 解决被邀请进入的群头像和名称不对问题
				if (oldNum.value !== list.length) {
					oldNum.value = list.length;
					list.map((item : any) => {
						if (!item.groupProfile?.avatar) {
							emits("isReLoad", item.conversationID);
						}
					})

				}
			},
			currentConversation: (conversation : IConversationModel) => {
				currentConversation.value = conversation;
			},
		});

		// 初始状态
		TUIStore.watch(StoreName.USER, {
			displayOnlineStatus: (status : boolean) => {
				displayOnlineStatus.value = status;
			},
			userStatusList: (list : Map<string, IUserStatus>) => {
				if (list.size !== 0) {
					userOnlineStatusMap.value = [...list.entries()].reduce(
						(obj, [key, value]) => {
							obj[key] = value;
							return obj;
						},
						{} as IUserStatusMap
					);
				}
			},
		});
	});

	onUnmounted(() => {

		TUIStore.unwatch(StoreName.CONV, {
			currentConversationID: (id : string) => {
				currentConversationID.value = id;
			},
			conversationList: (list : IConversationModel[]) => {
				let user_id = uni.getStorageSync("user_id");
				if (!user_id) {
					conversationList.value = [];
					return;
				}
				let arr : any[] = [];
				if (list?.length > 0) {
					list.map((item : any) => {
						item.show = false;
						arr.push(item);
					})
				}
				conversationList.value = arr;
				// 解决被邀请进入的群头像和名称不对问题
				if (oldNum.value !== list.length) {
					oldNum.value = list.length;
					list.map((item : any) => {
						if (!item.groupProfile?.avatar) {
							emits("isReLoad", item.conversationID);
						}
					})

				}
			},
			currentConversation: (conversation : IConversationModel) => {
				currentConversation.value = conversation;
			},
		});

		// 初始状态
		TUIStore.unwatch(StoreName.USER, {
			displayOnlineStatus: (status : boolean) => {
				displayOnlineStatus.value = status;
			},
			userStatusList: (list : Map<string, IUserStatus>) => {
				if (list.size !== 0) {
					userOnlineStatusMap.value = [...list.entries()].reduce(
						(obj, [key, value]) => {
							obj[key] = value;
							return obj;
						},
						{} as IUserStatusMap
					);
				}
			},
		});
	});

	const isShowUserOnlineStatus = (conversation : IConversationModel) : boolean => {
		return (
			displayOnlineStatus.value &&
			conversation.type === TUIChatEngine.TYPES.CONV_C2C
		);
	};

	const closeConversationActionMenu = () => {
		// 防止连续触发overlay的tap事件
		if (
			lastestOpenActionsMenuTime &&
			Date.now() - lastestOpenActionsMenuTime > 300
		) {
			currentConversation.value = undefined;
			isShowOverlay.value = false;
		}
	};

	const enterConversationChat = (conversationID : string) => {
		lastestOpenActionsMenuTime = Date.now();
		emits("handleSwitchConversation", conversationID);
		// TUIConversationService.switchConversation(conversationID);
	};

	const transformText = (val : string) => {
		let newVal = val.indexOf("TUIChat.") > -1 ? val.replace("TUIChat.", "") : val;

		return newVal;
	}
</script>

<style lang="scss" scoped src="./style/index.scss"></style>
<style lang="scss" scoped>
	.oh {
		overflow: hidden;
	}

	.TUI-conversation-item {
		.left_pic {
			width: 88rpx;
			height: 88rpx;
			margin-right: 24rpx;
		}

		.left_content {
			padding-left: 0;

			.content-header-label .name {
				font-size: 32rpx;
				color: #1D1D1D;
				margin-bottom: 16rpx;
			}


		}
	}

	::v-deep .u-swipe-view {
		.u-btn-text {
			font-size: 28rpx;
			width: 80%;
			text-align: center;
		}
	}

	.list_wrap {
		display: flex;
		flex-wrap: nowrap;
		align-items: stretch;
		position: relative;
		left: 0;
		transition: all 0.3s;

		.list_item {
			position: relative;
			width: 100%;
			flex: none;
		}

		.item_btn {
			flex: none;
			display: inline-flex;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			line-height: 36rpx;
			color: #fff;
			width: 180rpx;
			text-align: center;
		}

		.item_btn1 {
			background-color: #ff5d5d;
		}

		.item_btn2 {
			background-color: #ff8e35;
		}

		.item_btn3 {
			background-color: #7fd064;
		}

		&.active {
			left: -540rpx;
		}
	}
</style>